package com.kmzx.one.project.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kmzx.one.common.exceptions.NoSuchObjectException;
import com.kmzx.one.common.exceptions.ParameterNullException;
import com.kmzx.one.common.utils.ServletUtils;
import com.kmzx.one.common.utils.StringUtils;
import com.kmzx.one.common.utils.UUIDGenerator;
import com.kmzx.one.project.entity.AttributeWithCategory;
import com.kmzx.one.project.entity.Product;
import com.kmzx.one.project.entity.ProductAttributeValues;
import com.kmzx.one.project.entity.UserShoppingCart;
import com.kmzx.one.project.mapper.CustomerMapper;
import com.kmzx.one.project.mapper.ProductMapper;
import com.kmzx.one.project.mapper.UserCartMapper;
import com.kmzx.one.project.mapper.UserRankMapper;
import com.kmzx.one.project.others.common.PrivilegesUserData;
import com.kmzx.one.project.others.dso.ProdCatePriceDso;
import com.kmzx.one.project.others.dso.ProdJoinDiscount;
import com.kmzx.one.project.others.dso.ProductExtraInfo;
import com.kmzx.one.project.others.dso.UserRankDso;
import com.kmzx.one.project.others.dto.CartDiscountInfo;
import com.kmzx.one.project.others.dto.FastProdInfo;
import com.kmzx.one.project.others.dto.ProdOutInfo;
import com.kmzx.one.project.others.dto.StraightInfo;
import com.kmzx.one.project.others.dto.UserCartInfo;
import com.kmzx.one.project.others.dto.UserRankInfo;
import com.kmzx.one.project.others.dto.WareHouseInfo;
import com.kmzx.one.project.service.UserCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserCartServiceImpl implements UserCartService {

    @Autowired
    private UserCartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserRankMapper userRankMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public List<UserCartInfo> findMyShoppingCart() throws Exception {
        String userId = ServletUtils.getRequestUserId();
        Integer pageNum = ServletUtils.getRequestPageNum();
        Integer pageSize = ServletUtils.getRequestPageSize();
        List<String> specUsers = customerMapper.findSpecificUser();
        boolean spec = false;
        if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {
            if (specUsers.contains(userId)) {
                spec = true;
            }
        }
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;

        if (StringUtils.isEmpty(userId)) {
            throw new ParameterNullException("userId为空");
        }
        PageHelper.startPage(pageNum, pageSize, true);
        Page<UserCartInfo> result = cartMapper.selectUserCartAll(userId);

        if (CollectionUtils.isEmpty(result)) {
            return Collections.EMPTY_LIST;
        }

//        List<String> prodIds = result.stream().map(st -> st.getProdId()).collect(Collectors.toList());
        List<String> attributeValuesId = result.stream().map(st -> st.getUnitId()).collect(Collectors.toList());

        HashMap<String, BigDecimal> one = new HashMap<>();
        HashMap<String, String[]> two = new HashMap<>();
        HashMap<String, String> three = new HashMap<>();
        HashMap<String, String> four = new HashMap<>();

        ArrayList<String> allNameIds = new ArrayList<>();

        List<AttributeWithCategory> allPrice = productMapper.selectAttributePrice(attributeValuesId);
        List<PrivilegesUserData> userData = productMapper.selectSkuSpecificMinPriceList(attributeValuesId);

        allPrice.forEach(category -> {
            one.put(category.getId(), category.getPrice());
            String allIds = category.getAllAttributeValuesId();
            String[] split = allIds.split(",");
            two.put(category.getId(), split);
            for (String s : split) {
                allNameIds.add(s);
            }
        });


        List<ProductAttributeValues> names = productMapper.selectProdNamesByAllIds(allNameIds);
        names.forEach(name -> {
            three.put(name.getId(), name.getCategoryValue());
            four.put(name.getId(), name.getCateImg());
        });


        List<WareHouseInfo> houseInfos = productMapper.selectProdAttributeStore(attributeValuesId);

        HashMap<String, Integer> hashMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(houseInfos)) {

            for (WareHouseInfo info : houseInfos) {
                String id = info.getAttributeWithCategoryId();
                Integer infoNum = hashMap.get(id);
                if (infoNum == null) {
                    hashMap.put(id, info.getNowNumber());
                } else {
                    hashMap.put(id, infoNum + info.getNowNumber());
                }
            }

        }


        // 所有的商品打折活动,包括所有的商品
        List<ProdJoinDiscount> discounts = productMapper.selectAllProductJoinDiscount();

//        List<ProductDiscount> discount = productMapper.selectProductDiscountList(prodIds);
        if (!CollectionUtils.isEmpty(discounts)) {
            Map<String, List<ProdJoinDiscount>> collect = discounts.stream().collect(Collectors.groupingBy(ProdJoinDiscount::getSkuId));

            for (UserCartInfo cartInfo : result) {
                String unitId = cartInfo.getUnitId();
                cartInfo.setProdPrice(one.get(unitId));
                cartInfo.setCurrentPrice(one.get(unitId));
                String prodId = cartInfo.getUnitId();
                List<ProdJoinDiscount> productDiscounts = collect.get(prodId);
                if (!CollectionUtils.isEmpty(productDiscounts)) {
                    ProdJoinDiscount productDiscount = productDiscounts.get(0);
                    Integer discountCate = productDiscount.getDiscountCate();
                    cartInfo.setDiscountImg(productDiscount.getDiscountImg());
                    if (discountCate == 0) {
                        if(productDiscount.getDiscountNum().compareTo(BigDecimal.ONE)!=0){
                            cartInfo.setCurrentPrice(cartInfo.getProdPrice().multiply(productDiscount.getDiscountNum()));
                            cartInfo.setKinds(1);
                        }
                    } else {
                        cartInfo.setKinds(1);
                        cartInfo.setCurrentPrice(productDiscount.getDiscountNum());
                    }
                }
                cartInfo.setBeauty(cartInfo.getCurrentPrice());
            }
        }


        StringBuilder builder = new StringBuilder();
        for (UserCartInfo dto : result) {
            String unitId = dto.getUnitId();
            if (!CollectionUtils.isEmpty(userData) && spec) {
                List<PrivilegesUserData> data = userData.stream().filter(ud -> ud.getProductId().equals(unitId)).collect(Collectors.toList());
                if (data != null && data.size() > 0) {
                    BigDecimal cost = data.get(0).getCost();
                    dto.setProdPrice(cost);
                    dto.setCurrentPrice(cost);
                    dto.setBeauty(dto.getCurrentPrice());

                }
            }
            String[] strings = two.get(unitId);
            int length = strings.length;
            for (int i = 0; i < length; i++) {
                if (i == length - 1) {
                    builder.append(three.get(strings[i]));
                } else {
                    builder.append(three.get(strings[i]) + ",");
                }
                String s = four.get(strings[i]);
                if (s != null && !s.equals("")) {
                    dto.setProdImg(s);
                }
            }
            Integer infoNum = hashMap.get(unitId);
            if (infoNum != null) {
                dto.setHas(true);
                dto.setNumber(infoNum);
            } else {
                dto.setHas(false);
            }
            dto.setAttributeNames(builder.toString());
            builder.delete(0, builder.length());
        }


        for (UserCartInfo cartInfo : result) {
            cartInfo.setExtraRate(BigDecimal.ZERO);
            cartInfo.setExtraMoney(BigDecimal.ZERO);
            Integer inOrOut = cartInfo.getInOrOut();
            if (inOrOut == 1) {
                List<ProductExtraInfo> extraInfos = productMapper.selectProdExtraInfo("");
                if (!CollectionUtils.isEmpty(extraInfos)) {
                    ProductExtraInfo extraInfo = extraInfos.get(0);
                    cartInfo.setExtraRate(BigDecimal.valueOf(extraInfo.getChargesNumber()));
                    cartInfo.setExtraMoney(extraInfo.getChargesPrice());
                }
            }

        }
        return result;
    }

    @Override
    public Integer doDelCart(String userId, String[] cartIdArr) throws Exception {
        List<String> list = Arrays.asList(cartIdArr);
//        cartMapper.selectCartByIds(list);

        Date date = new Date();
        Integer insert = cartMapper.delUserCart(userId, list, date);
        return insert;
    }

    @Override
    public Integer doAddCart(String userId, String productId, String skuId, Integer count) throws Exception {

        Product product = productMapper.selectProdById(productId);
        if (product == null) {
            throw new NoSuchObjectException("该商品不存在");
        }
        Integer states = product.getStates();
        if (states == 1) {
            throw new NoSuchObjectException("该商品已经下架");
        }


        AttributeWithCategory withCategory = productMapper.selectAttributeWithCategoryById(skuId);
        if (withCategory == null || (withCategory != null && withCategory.getDeleted() == 1)) {
            throw new NoSuchObjectException("该商品不存在");
        }
        if (withCategory != null && withCategory.getStates() == 1) {
            throw new NoSuchObjectException("该商品已经下架");
        }

        UserShoppingCart cart = null;
        List<UserShoppingCart> byUserIdSkuId = cartMapper.selectCartByUserIdSkuId(userId, skuId);
        Date date = new Date();
        boolean up = false;
        if (!CollectionUtils.isEmpty(byUserIdSkuId)) {
            cart = byUserIdSkuId.get(0);
            if (cart == null) {
                cart = new UserShoppingCart();
                cart.setId(UUIDGenerator.generate());
                cart.setChecked(0);
                cart.setCreateTime(date);
                cart.setUpdateTime(date);
                cart.setProductId(productId);
                cart.setUserId(userId);
                cart.setDeleted(0);
                cart.setProdNum(count);
                cart.setStates(0);
                cart.setUnitId(skuId);
            } else {
                Integer prodNum = cart.getProdNum();
                int prodNum1 = prodNum + count;
                cart.setProdNum(prodNum1);
                cart.setUpdateTime(date);
                up = true;
            }
        } else {
            cart = new UserShoppingCart();
            cart.setCreateTime(date);
            cart.setId(UUIDGenerator.generate());
            cart.setChecked(0);
            cart.setUpdateTime(date);
            cart.setDeleted(0);
            cart.setUserId(userId);
            cart.setProdNum(count);
            cart.setProductId(productId);
            cart.setStates(0);
            cart.setUnitId(skuId);
        }
        if (up) {
            cartMapper.updateByIdSelective(cart);
        } else {
            Integer insert = cartMapper.insert(cart);
        }
        return 0;
    }

    @Override
    public Integer doAddOrSubtractGoods(String cartId, Integer count) throws Exception {
        UserShoppingCart cart = cartMapper.selectByPrimaryKey(cartId);
        if (cart == null) {
            throw new NoSuchObjectException("该物品不存在");
        }
        Integer states = cart.getStates();
        if (states == 1) {
            throw new NoSuchObjectException("该物品已下架");
        }

        Date date = new Date();
        Integer deleted = cart.getDeleted();

        if (deleted == 1) {
            cart.setProdNum(0);
        } else {
            cart.setProdNum(count);
        }

        Integer prodNum = cart.getProdNum();
        if (prodNum < 0) {
            cart.setProdNum(0);
        }
        cart.setUpdateTime(date);

        int insert = cartMapper.updateByIdSelective(cart);
        return insert;
    }

    @Override
    public CartDiscountInfo findDiscountInfo(String userId) {
        List<UserRankDso> tabs = userRankMapper.selectAllRankTabs();
        // selectAllRankTabs
        UserRankInfo rankTabs = userRankMapper.selectUserRankTabs(userId);
        Map<String, BigDecimal> fee = productMapper.selectProductFreeFee();
        CartDiscountInfo info = new CartDiscountInfo();
        info.setGrowthValue(rankTabs.getGrowth());
        info.setDiscountNum(tabs.get(0).getRank1Rate());
        info.setOuterDiscountNum(tabs.get(0).getRank2Rate());
        info.setRankMoney(tabs.get(0).getRankPay());
        if (CollectionUtils.isEmpty(fee)) {
            info.setOuterMoney(BigDecimal.valueOf(199));
        } else {
            info.setOuterMoney(fee.get("fullMoney"));
        }
        int rankNum = rankTabs.getRankNo();
        if (rankNum == 3) {
            info.setIsTop(1);
        }
        if (rankTabs != null) {
            for (int i = 0; i < tabs.size(); i++) {
                if (tabs.get(i).getRankId().equals(rankTabs.getRankId()) && i != tabs.size() - 1) {
                    info.setDiscountNum(tabs.get(i + 1).getRank1Rate());
                    info.setOuterDiscountNum(tabs.get(i + 1).getRank2Rate());
                    info.setRankMoney(tabs.get(i).getRankPay());
                    break;
                }
                if (tabs.get(i).getRankId().equals(rankTabs.getRankId()) && i == 3) {
                    info.setDiscountNum(tabs.get(i).getRank1Rate());
                    info.setOuterDiscountNum(tabs.get(i).getRank2Rate());
                }
            }
        }
        return info;
    }

    @Override
    public Integer findSkuIdNum(String skuId) throws Exception {
        Integer num = productMapper.selectProdAttributeStoreId2(skuId);
        if (num == null) {
            return 0;
        }
        return num;
    }

    @Override
    public List<ProdOutInfo> getRecommendProdList(String userId, Integer pageNum, Integer pageSize) {
//        if(userId)
        List<UserRankDso> tabs = userRankMapper.selectAllRankTabs();
        String rankId = tabs.get(0).getRankId();
        if (userId != null && !userId.equals("")) {
            UserRankInfo rankTabs = userRankMapper.selectUserRankTabs(userId);
            rankId = rankTabs.getRankId();
        }

        Page<ProdOutInfo> result = cartMapper.selectProductByRankId(rankId);

        List<ProdOutInfo> end = result.getResult();
        if (end == null || end.size() == 0) {
            return Collections.emptyList();
        } else {

            List<String> prodIds = end.stream().map(qq -> qq.getProdId()).collect(Collectors.toList());
            List<ProdCatePriceDso> priceDsos = productMapper.selectProdGroupPriceList(prodIds);


            // 所有的商品打折活动,包括所有的商品
            List<ProdJoinDiscount> discounts = productMapper.selectAllProductJoinDiscount();

            boolean specific = false;
            List<String> specUsers = customerMapper.findSpecificUser();
            if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {
                if (specUsers.contains(userId)) {
                    specific = true;
                }
            }
            if (!CollectionUtils.isEmpty(priceDsos)) {
                Map<String, List<ProdCatePriceDso>> map = priceDsos.stream().collect(Collectors.groupingBy(ProdCatePriceDso::getProductId));


                if (specific) {
                    for (ProdOutInfo prod : end) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                        if (prodCatePriceDsos != null) {
                            BigDecimal miniCost = prodCatePriceDsos.get(0).getMiniCost();
                            prod.setCurrentPrice(miniCost);
                            prod.setBeauty(miniCost);
                            prod.setKinds(1);
                            prod.setHas(prodCatePriceDsos.get(0).getNomNumbers() > 0);
                        } else {
                            prod.setCurrentPrice(BigDecimal.ONE);
                            prod.setBeauty(BigDecimal.ONE);
                        }
                    }
                } else {
                    for (ProdOutInfo prod : end) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                        if (prodCatePriceDsos != null) {
                            BigDecimal miniPrice = prodCatePriceDsos.get(0).getMiniPrice();
                            prod.setHas(prodCatePriceDsos.get(0).getNomNumbers() > 0);
                            prod.setBeauty(miniPrice);
                            prod.setCurrentPrice(miniPrice);
                        } else {
                            BigDecimal price = productMapper.selectProdGroupPrice(prod.getProdId());
                            if (price == null) {
                                prod.setCurrentPrice(BigDecimal.ONE);
                                prod.setBeauty(BigDecimal.ONE);
                            } else {
                                prod.setCurrentPrice(price);
                                prod.setBeauty(price);
                            }
                        }
                    }
                    switchToFastProd(end, userId, discounts);
                }
            }
            return end;
        }
    }


    public List<ProdOutInfo> switchToFastProd(List<ProdOutInfo> end, String userId, List<ProdJoinDiscount> discounts) {
        //
        List<StraightInfo> infoList = productMapper.selectAllStraightInfo();
        if (infoList == null) {
            if (!CollectionUtils.isEmpty(discounts)) {
                Map<String, List<ProdJoinDiscount>> listMap = discounts.stream().collect(Collectors.groupingBy(ProdJoinDiscount::getProductId));

                for (ProdOutInfo prod : end) {
                    String prodId = prod.getProdId();
                    List<ProdJoinDiscount> joinDiscounts = listMap.get(prodId);
                    if (joinDiscounts != null) {
                        prod.setKinds(1);
                        Integer discountCate = joinDiscounts.get(0).getDiscountCate();
                        // 0折扣 1 一口价
                        if (discountCate != 0) {
                            prod.setCurrentPrice(joinDiscounts.get(0).getDiscountNum());
                        } else if (discountCate != 1) {
                            prod.setCurrentPrice(prod.getProdPrice().multiply(joinDiscounts.get(0).getDiscountNum()));
                        }
                        prod.setBeauty(prod.getCurrentPrice());
                        prod.setDiscountImg(joinDiscounts.get(0).getDiscountImg());
                    }
                }
            }
            return end;
        }
        if (infoList != null && infoList.size() > 0) {
            UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
            boolean had = false;
            if (userRankInfo != null) {

                List<FastProdInfo> fastProdList = new ArrayList<>();
                for (StraightInfo info : infoList) {
                    String id = info.getId();
                    had = true;
                    Page<FastProdInfo> infos = productMapper.selectFastProdInfoPaged(id);
                    fastProdList.addAll(infos.getResult());
                }
                if (had) {
                    for (ProdOutInfo prodOutInfo : end) {
                        for (FastProdInfo fastProdInfo : fastProdList) {
                            if (prodOutInfo.getProdId().equals(fastProdInfo.getProdId())) {
                                prodOutInfo.setFastIcon(fastProdInfo.getFastIcon());
                                prodOutInfo.setCurrentPrice(fastProdInfo.getCurrentPrice());
                                prodOutInfo.setBeauty(fastProdInfo.getBeauty());
                                prodOutInfo.setKinds(2);
                            }
                        }
                    }
                }
            } else {
                had = true;
                List<FastProdInfo> fastProdList = new ArrayList<>();
                for (StraightInfo info : infoList) {
                    String id = info.getId();
                    Page<FastProdInfo> infos = productMapper.selectFastProdInfoPaged(id);
                    fastProdList.addAll(infos.getResult());
                }
                if (had) {
                    for (ProdOutInfo prodOutInfo : end) {
                        for (FastProdInfo fastProdInfo : fastProdList) {
                            if (prodOutInfo.getProdId().equals(fastProdInfo.getProdId())) {
                                prodOutInfo.setFastIcon(fastProdInfo.getFastIcon());
                                prodOutInfo.setCurrentPrice(fastProdInfo.getCurrentPrice());
                                prodOutInfo.setBeauty(fastProdInfo.getBeauty());
                                prodOutInfo.setKinds(2);
                            }
                        }
                    }
                }
            }
        }
        return end;
    }

}


